package controllers;

import helpers.DateHelper;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import admin.data.EmailStatisticData;

import models.EmailStatisticModel;

@SuppressWarnings("serial")
public class EmailRedirectServlet extends HttpServlet {

	private static final Logger log = Logger
			.getLogger(EmailRedirectServlet.class.getName());

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		try {
			HttpSession ss = request.getSession();
			String[] splitted = request.getRequestURI().split("/");
			String redirectUrl = "";
			for (int i = 0; i < splitted.length; i++) {
				if (i > 1) {
					redirectUrl += "/" + splitted[i];
				}
			}

			EmailStatisticData statisticData = new EmailStatisticData();
			EmailStatisticModel statisticModel = statisticData
					.getStatisticByDateString(DateHelper.dateToString(
							new Date(), "MM/dd/yyyy"));
			if (statisticModel != null && !statisticModel.getDoc().isEmpty()) {
				statisticModel
						.setClickCount(statisticModel.getClickCount() + 1);

			} else {
				statisticModel = new EmailStatisticModel();
				statisticModel.setClickCount(1);
				statisticModel
						.setDateOfCreate(Calendar.getInstance().getTime());
				statisticModel.setDoc(DateHelper.dateToString(new Date(),
						"MM/dd/yyyy"));
			}
			statisticData.insert(statisticModel);
			ss.setAttribute("email_redirect", true);
			response.sendRedirect(redirectUrl);
		} catch (Exception e) {
			System.out
					.println("Error when try to view check out form with invalid url !");
			log.warning("Error when try to view check out form with invalid url !");
			log.warning(e.toString());
			e.printStackTrace();
			request.getRequestDispatcher("/pages/error.jsp").forward(request,
					response);
		}
	}
}
